﻿using System;
using System.Collections.Generic;
using AutoMapper;
using ERP.BLL.CategoryApp.Dtos;
using ERP.Common.Extensions;
using ERP.Common.Model;
using ERP.IDAL.IRepositories.basic;
using ERP.Model.Entities;

namespace ERP.BLL.CategoryApp
{
    public class CategoryService : ICategoryService
    {
        private readonly ICategoryRepository _categoryRepository;
        public CategoryService(ICategoryRepository categoryRepository)
        {
            _categoryRepository = categoryRepository;
        }

        public void Delete(Guid id)
        {
            _categoryRepository.Delete(it => it.ParentId == id);
            _categoryRepository.Delete(id);
        }

        public List<CategoryDto> GetCategoryList()
        {
            return Mapper.Map<List<CategoryDto>>(_categoryRepository.GetAllListAsync().Result);
        }

        public PagedResultModel<CategoryDto> GetCategoryPageList(int pageIndex, int pageSize)
        {
            return Mapper.Map<List<CategoryDto>>(_categoryRepository.LoadPageList(pageIndex, pageSize, out var rowCount, t => true,
                     t => t.Id, false)).ApplyToPage(pageIndex, pageSize, rowCount);
        }

        public int Insert(CategoryDto dto)
        {
            var category = _categoryRepository.FirstOrDefaultAsync(t => t.Name == dto.Name && t.ParentId == dto.ParentId).Result;
            return category != null ? 1 : (_categoryRepository.Insert(Mapper.Map<Category>(dto)) != null ? 0 : 1);
        }

        public bool Update(CategoryDto dto)
        {
            return _categoryRepository.UpdateAsync(Mapper.Map<Category>(dto)).Result != null;
        }
    }
}
